<template>
	<view class="content" >
		
		<view class="tabbar-wrap" >
			<view class="tabbar-menu" >
				<view class="status-bar" ></view>
				<view class="menu-list">
					<view v-for="(tab, index) in tabBars" :key="tab.id" :class="['menu-item', tabIndex==index ? 'active' : '']" @click="tapTab(index)">{{tab.name}}</view>
					<view  class="menu-item " @click="openIM(kefu,3)">客服</view>
					
				</view>
				<view class="contact-wrap" @click="openContact">
					<image class="contact-icon" src="/static/img/contact.png" mode=""></image>
				</view>
			</view>
			<view class="tabbar-content">
				
				
				<view v-if="tabIndex == 0" class="message-list">
					
					<!-- <view class="searchbox">
						<view class="search-wrap">
							<view class="uni-icon uni-icon-search"></view>
							<input class="input" confirm-type="search" placeholder="搜索 用户昵称/艾特米号/手机号" />
						</view>
					</view> -->
					
					<!-- 客服消息 -->
					<!-- <view class="message-item" @click="openIM(kefu,3)">
						<image class="avatar" :src="kefu.avatar" mode=""></image>
						<view class="message-data">
							<view class="name">{{kefu.name}}</view>
							<view class="content">{{kefu.content}}</view>
						</view>
						<view class="message-info">
							<view class="time">{{kefu.time | timeFormat}}</view>
							
							<view v-if="kefu.count > 0" class="count">{{kefu.count}}</view>
						</view>
					</view> -->
					
					<!-- 系统消息 -->
					<view v-if="admin.content != ''" class="message-item" @click="openIM(admin,1)">
						<image class="avatar" :src="admin.avatar" mode=""></image>
						<view class="message-data">
							<view class="name">{{admin.name}}</view>
							<view class="content">{{admin.content}}</view>
						</view>
						<view class="message-info">
							<view class="time">{{admin.time | timeFormat}}</view>
							<!-- <view v-if="admin.count > 0" class="red-dot"></view> -->
							<view v-if="admin.count > 0" class="count">{{admin.count}}</view>
						</view>
					</view>
					<!-- 最近访客 -->
					<view v-if="visitor.id != ''" class="message-item" @click="openWin('visitor')">
						<image class="avatar" src="/static/img/zuijinfangke.png" mode=""></image>
						<view class="message-data">
							<view class="name">最近访客</view>
							<view class="content">{{visitor.user.name}}看了你</view>
						</view>
						<view class="message-info">
							<view class="time">{{visitor.created_at | timeFormat}}</view>
							<view v-if="visitor_count > 0" class="count">{{visitor_count}}</view>
						</view>
					</view>
					<!-- 我喜欢的人 -->
					<view v-if="follow1.id != ''" class="message-item" @click="openWin('follow1')">
						<image class="avatar" src="/static/img/woxihuanderen.png" mode=""></image>
						<view class="message-data">
							<view class="name">我喜欢的人</view>
							<view class="content">你赞了{{follow1.user.name}}</view>
						</view>
						<view class="message-info">
							<view class="time">{{follow1.created_at | timeFormat}}</view>
							<view v-if="follow1_count > 0" class="count">{{follow1_count}}</view>
						</view>
					</view>
					<!-- 喜欢我的人 -->
					<view v-if="follow2.id != ''" class="message-item" @click="openWin('follow2')">
						<image class="avatar" src="/static/img/xihuanwoderen.png" mode=""></image>
						<view class="message-data">
							<view class="name">喜欢我的人</view>
							<view class="content">{{follow2.member.name}}赞了你</view>
						</view>
						<view class="message-info">
							<view class="time">{{follow2.created_at | timeFormat}}</view>
							<view v-if="follow2_count > 0" class="count">{{follow2_count}}</view>
						</view>
					</view>
					<!-- 用户消息 -->
					<uni-swipe-action>
						<uni-swipe-action-item v-for="(item, index) in c2cList" :options="options" :key="index" @change="swipeChange" @click="swipeClick($event, index)">
							<view class="message-item" @click="openIM(item,2)">
								<image class="avatar" :src="item.avatar + '?imageView2/1/w/100/h/100'" mode="aspectFill"></image>
								<view class="message-data">
									<view class="name">{{item.name}}</view>
									<view class="content">{{item.content}}</view>
								</view>
								<view class="message-info">
									<view class="time">{{item.time | timeFormat}}</view>
									<view v-if="item.count > 0" class="count">{{item.count}}</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
					<view v-if="admin.content == '' && c2cList.length == 0" class="empty-wrap">
						<image class="empty-icon" src="/static/img/empty.png" mode=""></image>
						<text class="empty-text">暂无消息</text>
					</view>
				</view>
				
				<view v-if="tabIndex == 1" class="message-list">
					
					<!-- 群组消息 -->
					<view  class="message-item addgroup"  @click="addGroup">
						<image class="avatar" src="/static/img/message/add_group.png" mode=""></image>
						<view class="message-data">
							<view class="name">添加群聊</view>
						</view>
						<view class="message-info">
							
						</view>
					</view>
					
					<view v-if="groupAdmin.content != ''" class="message-item" @click="openAdmin(groupAdmin)">
						<image class="avatar" :src="groupAdmin.avatar" mode=""></image>
						<view class="message-data">
							<view class="name">{{groupAdmin.name}}</view>
							<view class="content">{{groupAdmin.content}}</view>
						</view>
						<view class="message-info">
							<view class="time">{{groupAdmin.time | timeFormat}}</view>
							<!-- <view v-if="admin.count > 0" class="red-dot"></view> -->
							<view v-if="groupAdmin.count > 0" class="count">{{groupAdmin.count}}</view>
						</view>
					</view>
					<view class="message-item" v-for="(item, index) in groupList" :key="index" @click="openGroup(item)">
						<image class="avatar" :src="item.avatar + '?imageView2/1/w/100/h/100'" mode="aspectFill"></image>
						<view class="message-data">
							<view class="name">{{item.name}}</view>
							<view class="content">{{item.content}}</view>
						</view>
						<view class="message-info">
							<view class="time">{{item.time | timeFormat}}</view>
							<view v-if="item.count > 0" class="count">{{item.count}}</view>
						</view>
					</view>
					<view v-if="groupList.length == 0 && groupAdmin.content == ''" class="empty-wrap">
						<image class="empty-icon" src="/static/img/empty.png" mode=""></image>
						<text class="empty-text">暂无消息</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import util from "@/common/util.js"
	import uniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'
	import uniSwipeActionItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue'
	export default {
		components: {
			uniSwipeAction,
			uniSwipeActionItem
		},
		data() {
			return {
				userInfo: {},
				scrollLeft: 0,
				tabIndex: 0,
				tabBars: [
					{
						name: '消息',
						id: 'message'
					},
					// {
					// 	name: '群组',
					// 	id: 'group'
					// }
				],
				kefu: {
					conversationID: '',
					id: '',
					avatar: '',
					name: '客服',
					content: '',
					time: 0,
					count: 0
				},
				
				admin: {
					conversationID: 'C2Cadmin',
					id: 'admin',
					avatar: '/static/img/admin_msg.png',
					name: '系统消息',
					content: '',
					time: 0,
					count: 0
				},
				groupAdmin: {
					conversationID: '',
					id: 'groupAdmin',
					avatar: '/static/img/admin_msg.png',
					name: '群通知消息',
					content: '',
					time: 0,
					count: 0
				},
				c2cList: [],
				groupList: [],
				visitor_list: [],
				visitor_count: 0,
				visitor: {
					id: '',
					created_at: '2019-10-06 13:50:00',
					user: {
						name: '',
					}
				},
				follow1_list: [],
				follow1_count: 0,
				follow1: {
					id: '',
					created_at: new Date().getTime(),
					user: {
						name: '',
					}
				},
				follow2_list: [],
				follow2_count: 0,
				follow2: {
					id: '',
					created_at: new Date().getTime(),
					member: {
						name: '',
					}
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: 'rgb(255,58,49)'
					}
				}]
			}
		},
		onLoad() {
			try {
				const myInfo = uni.getStorageSync('myInfo');
				if (myInfo) {
					this.userInfo = myInfo;
				}
				
				const kefuid = uni.getStorageSync('kefuid');
				this.kefu.conversationID='C2C' + this.IDBEFORE + kefuid;
				this.kefu.id=this.IDBEFORE + kefuid;
				
			} catch (e) {
				console.warn(e)
			}
			uni.$on('message-page', data => {
				this.getRecentContactList();
				// if (!!data && data.type == 'update') {
				// 	this.getRecentContactList();
				// }
				if (!!data && data.type == 'message') {
					// 收到新消息
					if (data.data.payload.data == 'like') {
						this.$tim.setMessageRead({
							conversationID: data.data.conversationID,
						});
						let custom_ext = JSON.parse(data.data.payload.extension)
						if (data.data.to == this.userInfo.id) {
							if (this.follow2.member.id != custom_ext.fromId) {
								this.follow2.member.name = custom_ext.fromName;
								this.follow2.created_at = data.data.time
								this.follow2_count = parseInt(this.follow2_count) + 1;
							}
						}
					}
				}
			})
			this.getUserVisitor();
			this.getUserFollow(1);
			this.getUserFollow(2);
			this.getRecentContactList();
			
		},
		onReady() {
			this.getUserVisitor();
			this.getUserFollow(1);
			this.getUserFollow(2);
			this.getRecentContactList();
		},
		onPullDownRefresh() {
			this.$api.api.ajaxData({
				method: 'V1.CacheFlush',
			}, res => {
				if (res.status) {
					// console.log('请求成功')
				}
			})
			
			setTimeout(() => {
				this.getUserVisitor();
				this.getUserFollow(1);
				this.getUserFollow(2);
				this.getRecentContactList();
			}, 500)
		},
		onShow() {
			this.$api.api.ajaxData({
				method: 'V1.CacheFlush',
			}, res => {
				if (res.status) {
					
				}
			})
			this.getUserVisitor();
			this.getUserFollow(1);
			this.getUserFollow(2);
			this.getRecentContactList();
		},
		
		methods: {
			swipeChange(e) {
				
			},
			swipeClick(e, index) {
				let { content } = e
				
				if (content.text === '删除') {
					uni.showModal({
						title: '提示',
						content: '是否删除',
						success: res => {
							if (res.confirm) {
								this.$tim.deleteConversation(this.c2cList[index].conversationID).then(imResponse => {
									console.log('被删除的会话 ID', imResponse.data)
									this.c2cList.splice(index, 1)
								}).catch(imError => {
									console.warn('删除会话失败', imError);
								});
							}
						}
					});
				}
			},
			
			tapTab: function(index) {
				if (this.tabIndex == index) {
					return false;
				}
				this.tabIndex = index
			},
			
			openContact: function () {
				uni.navigateTo({
					url: 'contact'
				})
			},
			
			getUserVisitor: function () {
				this.$api.api.ajaxData({
					method: 'V1.UserVisitor',
					uid: this.userInfo.id,
					token: this.userInfo.token,
					page: 1
				}, res => {
					if (res.status) {
						if (res.data.list.length > 0) {
							this.visitor_list = res.data.list
							this.visitor = res.data.list[0]
						}
					}
				})
			},
			
			getUserFollow: function (type) {
				this.$api.api.ajaxData({
					method: 'V1.UserFollow',
					uid: this.userInfo.id,
					token: this.userInfo.token,
					type: type,
					page: 1
				}, res => {
					
					if (res.status) {
						var resdata=res.data.data;
						if (type == 1) {
							if (resdata.length > 0) {
								this.follow1_list = resdata
								this.follow1 = resdata[0]
							}else{
								this.follow1.id='';
							}
						}
						if (type == 2) {
							if (resdata.length > 0) {
								this.follow2_list = resdata
								this.follow2 = resdata[0]
							}else{
								this.follow2.id='';
							}
						}
					}
				})
			},
			
			openIM: function (item,types) {
				uni.navigateTo({
					url: 'im?to=' + encodeURIComponent(JSON.stringify(item))+'&type='+types
				});
			},
			
			openWin: function (url) {
				this.$api.api.ajaxData({
					method: 'V1.CacheFlush',
				}, res => {
					if (res.status) {
						
					}
				})
				// if (url == 'visitor') {
				// 	getApp().globalData.visitor_list = this.visitor_list;
				// }
				// if (url == 'follow1') {
				// 	getApp().globalData.follow1_list = this.follow1_list;
				// }
				if (url == 'follow2') {
					if (this.userInfo.vip == 0) {
						uni.showModal({
							title: '提示',
							content: '查看喜欢我的人，请充值VIP',
							success: res => {
								if (res.confirm) {
									uni.navigateTo({
										url: '../my/vip'
									})
								}
							}
						})
						return false;
					}
					// getApp().globalData.follow2_list = this.follow2_list;
					this.follow2_count = 0;
				}
				uni.navigateTo({
					url: url
				});
			},
			// 跳转创建群聊
			addGroup(){
				
				uni.navigateTo({
					url: 'addGroup'
				});
			},
			openAdmin: function (item) {
				uni.navigateTo({
					url: 'system?to=' + JSON.stringify(item)
				});
			},
			
			openGroup: function (item) {
				uni.navigateTo({
					url: 'group_chat?to=' + JSON.stringify(item)
				});
				// console.log('打印群信息',item)
			},
			
			getRecentContactList: function() {
				let c2cList = [];
				let groupList = [];
				// uni.showLoading({
				// 	title: ''
				// });
				this.$tim.getConversationList().then(imResponse => {
					// uni.hideLoading();
					uni.stopPullDownRefresh();
					
					const conversationList = imResponse.data.conversationList;
					let unreadCount = 0;
					
					for (let i = 0; i < conversationList.length; i++) {
						unreadCount += conversationList[i].unreadCount;
						if (conversationList[i].type == 'C2C') {
							let content = '';
							if (conversationList[i].lastMessage.type == 'TIMTextElem') {
								content = conversationList[i].lastMessage.payload.text;
							}
							if (conversationList[i].lastMessage.type == 'TIMCustomElem') {
								if (conversationList[i].lastMessage.payload.data == 'gift' || conversationList[i].lastMessage.payload.data == 'img' || conversationList[i].lastMessage.payload.data == 'voice' || conversationList[i].lastMessage.payload.data == 'addFriend' || conversationList[i].lastMessage.payload.data == 'like') {
									content = '['+conversationList[i].lastMessage.payload.description+']';
								}
							}
							
							if (conversationList[i].userProfile.userID == 'admin') {
								this.admin.time = conversationList[i].lastMessage.lastTime;
								this.admin.count = conversationList[i].unreadCount;
								this.admin.content = content;
							} else {
								if(conversationList[i].userProfile.userID == this.kefu.id){
									
									this.kefu.time = conversationList[i].lastMessage.lastTime;
									this.kefu.count = conversationList[i].unreadCount;
									this.kefu.content = content;
								}else{
									c2cList.push({
										conversationID: conversationList[i].conversationID,
										id: conversationList[i].userProfile.userID,
										avatar: conversationList[i].userProfile.avatar,
										name: conversationList[i].userProfile.nick,
										content: content,
										time: conversationList[i].lastMessage.lastTime,
										count: conversationList[i].unreadCount
									})
								}
								
							}
						}
						if (conversationList[i].type == 'GROUP') {
							let content = '';
							if (conversationList[i].lastMessage.type == 'TIMTextElem') {
								content = conversationList[i].lastMessage.payload.text;
							}
							if (conversationList[i].lastMessage.type == 'TIMCustomElem') {
								if (conversationList[i].lastMessage.payload.data == 'gift' || conversationList[i].lastMessage.payload.data == 'img' || conversationList[i].lastMessage.payload.data == 'voice' ) {
									content = '['+conversationList[i].lastMessage.payload.description+']';
								}
							}
							groupList.push({
								conversationID: conversationList[i].conversationID,
								id: conversationList[i].groupProfile.groupID,
								avatar: !!conversationList[i].groupProfile.avatar ? conversationList[i].groupProfile.avatar : this.userInfo.avatar,
								name: conversationList[i].groupProfile.name,
								content: content,
								time: conversationList[i].lastMessage.lastTime,
								count: conversationList[i].unreadCount
							})
						}
						if (conversationList[i].type == '@TIM#SYSTEM') {
							if (conversationList[i].lastMessage.type == 'TIMGroupSystemNoticeElem') {
								this.groupAdmin.conversationID = conversationList[i].conversationID,
								this.groupAdmin.time = conversationList[i].lastMessage.lastTime;
								this.groupAdmin.count = conversationList[i].unreadCount;
								this.groupAdmin.content = '群通知';
							}
						}
					}
					this.c2cList = c2cList;
					this.groupList = groupList;
					if (unreadCount == 0) {
						uni.removeTabBarBadge({
							index: 3
						})
					} else {
						uni.setTabBarBadge({
						  index: 3,
						  text: unreadCount.toString()
						})
					}
				}).catch(imError => {
					console.warn('获取会话列表失败:', imError);
				});
			},
			
			getGroupList: function () {
				this.$tim.getGroupList().then(imResponse => {
					// console.log('获取群组列表', JSON.stringify(imResponse.data.groupList));
					for (let i = 0; i < imResponse.data.groupList.length; i++) {
						for (let j = 0; j < this.groupList.length; j++) {
							if (imResponse.data.groupList[i].groupID != this.groupList[j].id) {
								this.groupList.push({
									conversationID: 'GROUP' + imResponse.data.groupList[i].groupID,
									id: imResponse.data.groupList[i].groupID,
									avatar: !!imResponse.data.groupList[i].avatar ? imResponse.data.groupList[i].avatar : this.userInfo.avatar,
									name: imResponse.data.groupList[i].name,
									content: '',
									time: imResponse.data.groupList[i].selfInfo.joinTime,
									count: 0
								})
								break;
							}
						}
					}
				}).catch(function(imError) {
					console.warn('获取群组列表失败的相关信息', imError);
				});
			},
			
		   
		},
		filters: {
			timeFormat: function (value) {
				let now = new Date().getTime();
				let old = value
				let	oldTime = 0
				if (typeof value === 'number') {
					oldTime = old*1000;
				}
				if (typeof value === 'string') {
					oldTime = new Date(value.replace(/-/g, '/')).getTime();
				}
				return util.dateUtils.humanize(now - oldTime);
			},
		}
	}
</script>

<style lang="scss">
	@import '../../common/common.scss';
	.status-bar {
		background-color: #666;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 9;
		height:var(--status-bar-height);
	}

	.tabbar-menu {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		width: 100%;
		background-color: #fff;
		// border-bottom: 1rpx solid #f7f7f7;
		// padding-top: var(--status-bar-height);
		position: fixed;
		left: 0;
		top:var(--status-bar-height);
		z-index: 9;

		.menu-list {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			flex: 1;
			padding: 0 20rpx;

			.menu-item {
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 20rpx;
				font-size: 36rpx;
				text-align: center;
				color: #999;
				position: relative;

				&.active {
					color: #EE3476;
				}
               
				&.active::after {
					content: '';
					width: 20rpx;
					height: 10rpx;
					background: #EE3476;
					border-radius: 10rpx;
					position: absolute;
					left: 50%;
					bottom: 0;
					margin-left: -10rpx;
				}
			}
		}

		.contact-wrap {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 80rpx;
			padding: 0 20rpx;

			.contact-icon {
				width: 50rpx;
				height: 50rpx;
				margin-right: 10rpx;
			}

			text {
				font-size: 30rpx;
				color: #333;
			}
		}
	}

	.tabbar-content {
		margin-top: var(--status-bar-height);
		padding-top: 80rpx;
	}

	.searchbox{
		background-color: #FFFFFF;
		padding: 10rpx 20rpx 20rpx 20rpx;
		.search-wrap {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			background: #efefef;
			padding: 0 40rpx 0 20rpx;
			border-radius: 10rpx;
		    height: 70rpx !important;
			.uni-icon {
				font-size: 36rpx;
				color: #666;
			}
		
			.input {
				flex: 1;
				height: 60rpx;
				padding: 0 10rpx;
				line-height: 60rpx;
				font-size: 30rpx;
				box-sizing: border-box;
			}
		}
	}
	

	.message-item {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		padding: 20rpx;
		background: #fff;
		// border-bottom: 1px solid #efefef;
		box-sizing: border-box;

		.avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 100rpx;
			background-color: $image-bg-color;
		}

		.message-data {
			flex: 1;
			margin: 0 10rpx;

			.name {
				font-size: 32rpx;
				color: #333;
			}

			.content {
				font-size: 28rpx;
				color: #777;
				height: 48rpx;
				overflow: hidden;
			}
		}

		.message-info {
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
			align-items: flex-end;

			.time {
				font-size: 28rpx;
				color: #777;
			}
			
			.red-dot {
				width: 20rpx;
				height: 20rpx;
				background-color: #f00;
				border-radius: 20rpx;
				margin-top: 10rpx;
			}
			
			.count {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 30rpx;
				height: 30rpx;
				background-color: #f00;
				border-radius: 30rpx;
				font-size: 16rpx;
				color: #fff;
				margin-top: 10rpx;
			}
		}
	}

</style>
